package indv.Cning.cfengsecuritydemo.session;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Cfeng
 * @date 2022/7/24
 * 会话管理工具，可以强制下线,还是创建一个单例Bean
 */

@Component
@RequiredArgsConstructor   //创建一个构造器
public class SessionUtils {

    //引入sessionRegistry对象，config中配置的Impl,可以获取当前登录的所有用户
    private final SessionRegistry sessionRegistry;

    public void expireUserSessions(String userName) {
        for(Object principal : sessionRegistry.getAllPrincipals()) {
            UserDetails userDetails = (UserDetails) principal;
            //找到Session中的principal找到对应的用户,获取到当前用户的所有info，allSessions
            if(userDetails.getUsername().equals(userName)) {
                List<SessionInformation> sessionInfos = sessionRegistry.getAllSessions(userDetails,true);
                for(SessionInformation sessionInformation : sessionInfos) {
                    //让存储的session立刻失效
                    sessionInformation.expireNow();
                }
            }
        }
    }
}
